package cn.edu.scnu.controller;

import cn.edu.scnu.config.AliPayConfig;
import cn.edu.scnu.entity.Member;
import cn.edu.scnu.mapper.MemberMapper;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    AliPayConfig aliPayConfig;
    @Resource
    private MemberMapper memberMapper;
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    /**
     * 支付接口
     * @param httpResponse
     * @return
     * @throws Exception
     */
    @GetMapping("/pay")
    public String pay(HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        // 设置 NotifyUrl 和 ReturnUrl
        String notifyUrl = "http://localhost:8080/alipay/notify";  // 本地开发环境 URL
        String returnUrl = "http://localhost:8080/alipay/return";  // 本地开发环境 URL
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        String tradeNo = LocalDateTime.now().toString();
        int price = 100;
        String subject = "电影会员充值";
        request.setBizContent("{\"out_trade_no\":\"" + tradeNo + "\","
                + "\"total_amount\":\"" + price + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            System.out.println("qr_code:" + response.getSubCode());
            return "{\"qr_code\": \"" + response.getBody() + "\"}";
        } else {
            System.out.println("failed:" + response.getMsg() + ":" + response.getSubMsg());
            return "{\"error\": \"" + response.getMsg() + ": " + response.getSubMsg() + "\"}";
        }
    }

    /**
     * 异步通知接口
     * @param request
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/notify")
    public String handleNotify(HttpServletRequest request, HttpSession session) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
        if (signVerified) {
            System.out.println("Async notification received and verified.");
            Member member = (Member) session.getAttribute("member");
            if (member != null) {
                member.setVip(1);
                memberMapper.updateById(member);  // 更新数据库中的会员状态
                session.setAttribute("member", member);  // 更新会话中的会员状态（可选）
            }
            return "success";
        } else {
            System.out.println("Async notification verification failed.");
            return "failure";
        }
    }

    @GetMapping("/return")
    public RedirectView handleReturn(HttpServletRequest request, HttpSession session) {
        Member member = (Member) session.getAttribute("member");
        if (member != null) {
            member.setVip(1);
            memberMapper.updateById(member);  // 更新数据库中的会员状态
            session.setAttribute("member", member);  // 更新会话中的会员状态（可选）
        }
        return new RedirectView("/index");
    }


}
